import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(), // 设置token为共享
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步缓存
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    // 同步删除
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo

  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  // data :{mobile , password}
  async login(context, data) {
    const res = await login(data)

    context.commit('setToken', res)

    setTimeStamp()

  },
  // 获取用户资料
  async getUserInfo(context) {
    const res = await getUserInfo()
    // 获取用户详细信息
    const baseInfo = await getUserDetailById(res.userId)


    context.commit('setUserInfo', { ...res, ...baseInfo })
    return res
  },

  // 登出
  logout({ commit }) {
    // 删除token
    commit('removeToken')
    // 删除用户资料
    commit('removeUserInfo')
    // 重置路由
    resetRouter()
    // 初始化路由信息 commit 默认提交当前子模块的mutations
    // 加上root:true 则可以调用根级别的mutations
    commit('permission/setRoutes',[],{ root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}